package tr.edu.metu.is.mega.client.widgets;

import com.extjs.gxt.ui.client.widget.form.AdapterField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.google.gwt.user.client.ui.Widget;

/**
 * Abstract class for custom validatable components.
 * 
 */
public abstract class MegaCompositeField extends AdapterField implements MegaField {

    private Validator validator;

    /**
     * Default constructor.
     * 
     * @param widget widget
     */
    public MegaCompositeField(Widget widget) {
        super(widget);
    }

    /**
     * Sets validator.
     * 
     * @param validator validator
     */
    public void setValidator(Validator validator) {
        this.validator = validator;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean validateValue(String value) {
        if (validator != null) {
            String msg = validator.validate(this, value);
            if (msg != null) {
                markInvalid(msg);
                return false;
            }
        }
        return true;
    }

    /**
     * Returns whether or not the field value is currently valid.
     * 
     * @param preventMark true for silent validation (no invalid event and field
     *        is not marked invalid)
     * 
     * @return <code>true</code> if the value is valid, otherwise
     *         <code>false</code>
     */
    @Override
    public boolean isValid(boolean preventMark) {
        if (disabled) {
            return true;
        }
        boolean restore = this.preventMark;
        this.preventMark = preventMark;
        boolean result = validateValue(getRawValue());
        this.preventMark = restore;
        return result;
    }

    /**
     * 
     * {@inheritDoc}
     */
    @Override
    public Object getValue() {
        return ((MegaCompositeWidget) getWidget()).getWidgetValue();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setValue(Object value) {
        if(value != null){
            ((MegaCompositeWidget) getWidget()).setWidgetValue(value);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getRawValue() {
        Object value = ((MegaCompositeWidget) getWidget()).getWidgetValue();
        if (value != null) {
            return value.toString();
        }
        return null;
    }

}
